using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;

namespace axCommerce.Data
{
	[DataObject]
	[Serializable]
	public partial class Purchase
	{
		#region Constants

		private const string TableName = "[dbo].[Purchase]";

		#endregion

		#region Properties

		public int? PurchaseId { get; set; }
		public int? OrderId { get; set; }
		public int? ProductId { get; set; }
		public int? Quantity { get; set; }
		public DateTime? CreatedDate { get; set; }
		public DateTime? LastModifiedDate { get; set; }
		public bool? IsDeleted { get; set; }

		#endregion

		#region Methods

		#region Mapping Methods

		protected void MapTo(DataSet ds)
		{
			if (ds == null)
				ds = new DataSet();

			if (ds.Tables[TableName] == null)
				ds.Tables.Add(TableName);

			ds.Tables[TableName].Columns.Add("PurchaseId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("OrderId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("ProductId", typeof (Int32));
			ds.Tables[TableName].Columns.Add("Quantity", typeof (Int32));
			ds.Tables[TableName].Columns.Add("CreatedDate", typeof (DateTime));
			ds.Tables[TableName].Columns.Add("LastModifiedDate", typeof (DateTime));
			ds.Tables[TableName].Columns.Add("IsDeleted", typeof (Boolean));

			DataRow dr = ds.Tables[TableName].NewRow();

			dr["PurchaseId"] = PurchaseId ?? (object) DBNull.Value;
			dr["OrderId"] = OrderId ?? (object) DBNull.Value;
			dr["ProductId"] = ProductId ?? (object) DBNull.Value;
			dr["Quantity"] = Quantity ?? (object) DBNull.Value;
			dr["CreatedDate"] = CreatedDate ?? (object) DBNull.Value;
			dr["LastModifiedDate"] = LastModifiedDate ?? (object) DBNull.Value;
			dr["IsDeleted"] = IsDeleted ?? (object) DBNull.Value;

			ds.Tables[TableName].Rows.Add(dr);
		}

		protected void MapFrom(DataRow dr)
		{
			PurchaseId = dr["PurchaseId"] != DBNull.Value ? Convert.ToInt32(dr["PurchaseId"]) : PurchaseId = null;
			OrderId = dr["OrderId"] != DBNull.Value ? Convert.ToInt32(dr["OrderId"]) : OrderId = null;
			ProductId = dr["ProductId"] != DBNull.Value ? Convert.ToInt32(dr["ProductId"]) : ProductId = null;
			Quantity = dr["Quantity"] != DBNull.Value ? Convert.ToInt32(dr["Quantity"]) : Quantity = null;
			CreatedDate = dr["CreatedDate"] != DBNull.Value ? Convert.ToDateTime(dr["CreatedDate"]) : CreatedDate = null;
			LastModifiedDate = dr["LastModifiedDate"] != DBNull.Value
			                   	? Convert.ToDateTime(dr["LastModifiedDate"])
			                   	: LastModifiedDate = null;
			IsDeleted = dr["IsDeleted"] != DBNull.Value ? Convert.ToBoolean(dr["IsDeleted"]) : IsDeleted = null;
		}

		private static List<Purchase> MapFrom(DataSet ds)
		{
			// Initialise Collection.
			List<Purchase> objects = new List<Purchase>();

			// Validation.
			if (ds == null)
				throw new ApplicationException("Cannot map to dataset null.");
			
			if (ds.Tables[TableName].Rows.Count == 0)
				return objects;

			if (ds.Tables[TableName] == null)
				throw new ApplicationException("Cannot find table [dbo].[Purchase] in DataSet.");

			if (ds.Tables[TableName].Rows.Count < 1)
				throw new ApplicationException("Table [dbo].[Purchase] is empty.");

			// Map DataSet to Instance.
			foreach (DataRow dr in ds.Tables[TableName].Rows)
			{
				var instance = new Purchase();
				instance.MapFrom(dr);
				objects.Add(instance);
			}

			// Return collection.
			return objects;
		}

		#endregion

		#region CRUD Methods

		private static Purchase Get(Int32 purchaseId)
		{
			Purchase instance = new Purchase();

			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPurchase_SELECT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, purchaseId))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					if (ds == null || ds.Tables[0].Rows.Count == 0)
						throw new ApplicationException(String.Format("Could not get Purchase ID:{0} from Database.", purchaseId));
					// Return results.
					ds.Tables[0].TableName = TableName;

					instance.MapFrom(ds.Tables[0].Rows[0]);
				}
			}
			return instance;
		}

		#region INSERT

		private void Insert(Int32? orderId, Int32? productId, Int32? quantity, DateTime? createdDate,
		                    DateTime? lastModifiedDate, Boolean? isDeleted, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPurchase_INSERT";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, orderId, productId, quantity, createdDate, lastModifiedDate, isDeleted))
			{
				PurchaseId = Convert.ToInt32(transaction == null ? db.ExecuteScalar(dbCommand) : db.ExecuteScalar(dbCommand, transaction));
			}
		}

		/// <summary>
		/// Insert current Purchase to database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Insert(DbTransaction transaction = null)
		{
			Insert(OrderId, ProductId, Quantity, CreatedDate, LastModifiedDate, IsDeleted, transaction);
		}

		#endregion

		#region UPDATE

		private static void Update(Int32? purchaseId, Int32? orderId, Int32? productId, Int32? quantity, DateTime? createdDate,
		                           DateTime? lastModifiedDate, Boolean? isDeleted, DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPurchase_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@purchaseId"].Value = purchaseId;
				dbCommand.Parameters["@orderId"].Value = orderId;
				dbCommand.Parameters["@productId"].Value = productId;
				dbCommand.Parameters["@quantity"].Value = quantity;
				dbCommand.Parameters["@createdDate"].Value = createdDate;
				dbCommand.Parameters["@lastModifiedDate"].Value = lastModifiedDate;
				dbCommand.Parameters["@isDeleted"].Value = isDeleted;

				if (transaction == null)
					db.ExecuteNonQuery(dbCommand);
				else
					db.ExecuteNonQuery(dbCommand, transaction);
			}
		}

		private static void Update(Purchase purchase)
		{
			purchase.Update();
		}

		private static void Update(Purchase purchase, DbTransaction transaction)
		{
			purchase.Update(transaction);
		}

		/// <summary>
		/// Updates changes to the database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Update(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPurchase_UPDATE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
			{
				db.DiscoverParameters(dbCommand);
				dbCommand.Parameters["@purchaseId"].SourceColumn = "PurchaseId";
				dbCommand.Parameters["@orderId"].SourceColumn = "OrderId";
				dbCommand.Parameters["@productId"].SourceColumn = "ProductId";
				dbCommand.Parameters["@quantity"].SourceColumn = "Quantity";
				dbCommand.Parameters["@createdDate"].SourceColumn = "CreatedDate";
				dbCommand.Parameters["@lastModifiedDate"].SourceColumn = "LastModifiedDate";
				dbCommand.Parameters["@isDeleted"].SourceColumn = "IsDeleted";

				using (DataSet ds = new DataSet())
				{
					MapTo(ds);
					ds.AcceptChanges();
					ds.Tables[0].Rows[0].SetModified();
					if (transaction == null)
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, UpdateBehavior.Standard);
					else
						db.UpdateDataSet(ds, TableName, null, dbCommand, null, transaction);
				}
			}
		}

		#endregion

		#region DELETE

		private static void Delete(Int32? purchaseId, DbTransaction transaction)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPurchase_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, purchaseId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
		}

		/// <summary>
		/// Delete current Purchase from database.
		/// </summary>
		/// <param name="transaction">optional SQL Transaction</param>
		private void Delete(DbTransaction transaction = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPurchase_DELETE";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, PurchaseId))
			{
				if (transaction != null)
				{
					db.ExecuteNonQuery(dbCommand, transaction);
				}
				else
				{
					db.ExecuteNonQuery(dbCommand);
				}
			}
			PurchaseId = null;
		}

		#endregion

		#region SEARCH

		private static List<Purchase> Search(Int32? purchaseId = null, Int32? orderId = null, Int32? productId = null, Int32? quantity = null,
		                                     DateTime? createdDate = null, DateTime? lastModifiedDate = null, Boolean? isDeleted = null)
		{
			Database db = DatabaseFactory.CreateDatabase();
			const string sqlCommand = "[dbo].gspPurchase_SEARCH";
			using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand, purchaseId, orderId, productId, quantity, createdDate, lastModifiedDate, isDeleted))
			{
				using (DataSet ds = db.ExecuteDataSet(dbCommand))
				{
					ds.Tables[0].TableName = TableName;
					return MapFrom(ds);
				}
			}
		}


		private static List<Purchase> Search(Purchase searchObject)
		{
			return Search(searchObject.PurchaseId, searchObject.OrderId, searchObject.ProductId, searchObject.Quantity,
			              searchObject.CreatedDate, searchObject.LastModifiedDate, searchObject.IsDeleted);
		}

		#endregion

		#endregion

		#endregion
	}
}